package client;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import config.Config;

public class FastQueryGenerator {
	private static String [][]queries;
	private static int []position;
	
	private static String getGeneratedQueriesContent() {
		StringBuilder contents = new StringBuilder();
		try {
			//use buffering, reading one line at a time
			//FileReader always assumes default encoding is OK!
			String filePath = System.getProperty("user.home") + '/' + Config.generated_queries_file;
			BufferedReader input =  new BufferedReader(new FileReader(filePath));
			try {
				String line = null; //not declared within while loop
				/*
				* readLine is a bit quirky :
				* it returns the content of a line MINUS the newline.
				* it returns null only for the END of the stream.
				* it returns an empty String if two newlines appear in a row.
				*/
				while (( line = input.readLine()) != null) {
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			}
			finally {
				input.close();
			}
		}
		catch (IOException ex){
			ex.printStackTrace();
		}
		
		return contents.toString();
	}
	
	public static void initialize() {
		String []generatedQueries = getGeneratedQueriesContent().split("\\|");
		queries = new String[22][Config.same_query_count];
		position = new int[22];
		
		int q = 0, i = 0;
		for(String query : generatedQueries) {
			query = query.trim();
			if(query.isEmpty()) {
				continue;
			}
			
			queries[q][i] = query;
			i ++;
			
			if(i>=Config.same_query_count) {
				q ++;
				i = 0;
			}
		}
		
		for(i=0; i<22; i++) {
			position[i] = 0;
		}
	}
	
	public static String Q(int i) {
		String result = queries[i-1][position[i-1]];
		position[i-1] = (position[i-1] + 1) % Config.same_query_count;
		return result;
	}
}
